<template>
  <div class="profile">
    <el-card>
      <template #header>
        <span>个人信息</span>
      </template>
      
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="专业" prop="major">
          <el-input v-model="form.major" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="tele">
          <el-input v-model="form.tele" />
        </el-form-item>
        
        <el-form-item label="个人信息" prop="inf">
          <el-input 
            v-model="form.inf" 
            type="textarea" 
            :rows="4" 
            placeholder="请填写个人信息、生活习惯等"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updateProfile" :loading="loading">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../utils/request'

const formRef = ref()
const loading = ref(false)

const form = reactive({
  name: '',
  gender: '男',
  major: '',
  tele: '',
  inf: ''
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }]
}

const loadProfile = async () => {
  try {
    const response = await request.get('/api/student/profile')
    if (response.data.code === 200 && response.data.data) {
      Object.assign(form, response.data.data)
    }
  } catch (error) {
    console.error('加载个人信息失败:', error)
  }
}

const updateProfile = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await request.put('/api/student/profile', form)
        if (response.data.code === 200) {
          ElMessage.success('保存成功')
        }
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.profile {
  padding: 20px;
}
</style> 